<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="http://cdn.datatables.net/1.10.21/css/jquery.dataTables.css">
    <link rel="stylesheet" href="/static/css/bootstrap.min.css">
    <title>学生宿舍管理系统</title>
</head>
<body>

<!-- 导航栏 -->
<nav class="navbar navbar-default" role="navigation">
    <div class="container-fluid">
        <div class="navbar-header">
            <a class="navbar-brand" href="/">高校学生宿舍管理系统</a>
        </div>
        <div>
            <ul class="nav navbar-nav">
                <li class="active" id="manage"><a>宿舍管理</a></li>
                <li id="student"><a>学生信息</a></li>
            </ul>
        </div>
    </div>
</nav>

<!-- 登陆状态 -->
<div class="header" style="overflow: hidden">
    <div class="build_detail" style="margin: 10px; float: left"></div>
    {% if request.session.name %}
        <span style="float: right; line-height: 40px; margin-right: 30px">
            当前登陆用户：{{ request.session.name }}
            <a id="logout">注销</a>
        </span>
    {% else %}
        <a href="/login.html" id="logout">登陆</a>
    {% endif %}
</div>

<div class="table_body">
    <!-- 搜索 -->
    <form onsubmit="return search()" style="float: right; margin: 10px">
        <input type="text" name="title" id="title" placeholder="请输入搜索关键字" autocomplete="off">
        <input type="submit" value="搜索">
    </form>

    <!-- 宿舍管理 -->
    <table id="tableList" width="90%" style="text-align: center"></table>
</div>

<div class="student_table_body" style="display: none">
    <table id="StudentTableList" width="90%" style="text-align: center"></table>
</div>

<!-- 寝室详情modal框 -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="exampleModalLabel"></h4>
            </div>
            <div class="modal-body">
                <form>
                    <label for="recipient-name" class="control-label">迁入学生：</label>
                    <input type="text"
                           id="student_number" style="width: 200px" placeholder="输入学生学号" autocomplete="off">
                    <button type="button" class="btn btn-primary" id="move_in"
                            style="margin-left:30px;padding: 5px 10px;font-size: 12px">点击迁入
                    </button>
                </form>
                <label for="recipient-name" class="control-label" style="margin: 10px 0">已入住学生信息：</label>
                <table class="table" id="student_info">
                </table>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" data-dismiss="modal">确定</button>
            </div>
        </div>
    </div>
</div>

<!--迁出modal框-->
<div class="modal fade" id="move_out_model" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="move_out_room_name"></h4>
            </div>
            <div class="modal-body">
                <label for="recipient-name" class="control-label" style="margin: 10px 0">迁出学生信息：</label>
                <table class="table" id="move_out_student_info">
                </table>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="move_out_btn">确定</button>
            </div>
        </div>
    </div>
</div>

</body>
<script type='text/javascript' src="/static/js/jquery.min.js"></script>
<script type='text/javascript' src="/static/js/bootstrap.min.js"></script>
<script type="text/javascript" charset="utf8" src="http://cdn.datatables.net/1.10.21/js/jquery.dataTables.js"></script>
<script>
    const user_name = '{{ request.session.name }}' // 管理员姓名
    if (user_name === '') {
        window.location.href = '/login.html'
    }
    const user_id = '{{ request.session.id }}' // 管理员id
    const build_id = Number({{ request.session.build_id }}) // 楼宇id
    var sex // 宿舍性别
    var move_out_student_number // 迁出学生学号
    var move_out_room_id // 迁出寝室id
    var room_name // 模态框显示的名称
    var table // 定义表格
    var studentTable // 定义学生表格
    $(function () {
        createTable()
    })

    // 创建表格
    function createTable() {
        table = $('#tableList').DataTable({
            "bPaginate": true,
            "sPaginationType": "full_numbers",
            "bStateSave": true, //是否打开客户端状态记录功能,此功能在ajax刷新纪录的时候不会将个性化设定回复为初始化状态
            "bScrollCollapse": true, //当显示的数据不足以支撑表格的默认的高度
            "bLengthChange": true, //每页显示的记录数
            "bFilter": false, //搜索栏
            "bSort": true, //是否支持排序功能
            "bInfo": true, //显示表格信息
            "bAutoWidth": true, //自适应宽度
            "bJQueryUI": true,//是否开启主题
            "bDestroy": true,
            "bServerSide": false,//服务器处理分页，默认是false，需要服务器处理，必须true
            ajax: {
                url: "/build-manage/get-build-detail/", // 请求的url
                type: "get",
                dataSrc: function (result) {
                    if (result.data[0].detail == 1) {
                        sex_detatil = '男生寝室'
                    } else {
                        sex_detatil = '女生寝室'
                    }
                    var detail = "<span>楼宇名称:" + result.data[0].build_name + '（' + sex_detatil + '）' + "</span>"

                    $('.build_detail').html(detail)
                    sex = result.data[0].detail // 获取楼宇对应性别，方便后续的迁入管理，作性别判断
                    createStudentTable()
                    return result.data[0].allRoom;
                },
            },
            "columns": [
                {
                    "data": "id",
                    "title": "id",
                    "width": "auto",
                    "render": function (data, type, full, meta) {
                        return data;
                    }
                },
                {
                    "data": "name",
                    "title": "寝室号"
                },
                {
                    "data": "number",
                    "title": "床位数"

                },
                {
                    "data": "actual_number",
                    "title": "入住人数"
                },
                {
                    "data": "student_info",
                    "title": "入住学生",
                    "render": function (data, type, row, meta) {
                        let show_name = ''
                        for (let item in data) {
                            show_name += data[item].name + "-"
                        }
                        return show_name
                    }
                },
                {
                    "data": "bed_type",
                    "title": "操作",
                    "render": function () {
                        return '<a class="edit">查看编辑</a>'
                    }
                }
            ],
            /*请求携带参数*/
            "fnServerParams": function (aoData) {
                aoData.push(
                    {"name": "build_id", "value": build_id},
                );
            },
        });
    }


    function createStudentTable() {
        studentTable = $('#StudentTableList').DataTable({
            "bPaginate": true,
            "sPaginationType": "full_numbers",
            "bStateSave": true, //是否打开客户端状态记录功能,此功能在ajax刷新纪录的时候不会将个性化设定回复为初始化状态
            "bScrollCollapse": true, //当显示的数据不足以支撑表格的默认的高度
            "bLengthChange": true, //每页显示的记录数
            "bFilter": false, //搜索栏
            "bSort": true, //是否支持排序功能
            "bInfo": true, //显示表格信息
            "bAutoWidth": true, //自适应宽度
            "bJQueryUI": true,//是否开启主题
            "bDestroy": true,
            "bServerSide": false,//服务器处理分页，默认是false，需要服务器处理，必须true
            ajax: {
                url: "/get-student-info/", // 请求的url
                type: "get",
                dataSrc: function (result) {
                    return result.data
                },
            },
            "columns": [
                {
                    "data": "id",
                    "title": "id",
                    "width": "auto",
                    "render": function (data, type, full, meta) {
                        return data;
                    }
                },
                {
                    "data": "name",
                    "title": "姓名"
                },
                {
                    "data": "student_number",
                    "title": "学号"

                },
                {
                    "data": "phone",
                    "title": "电话"
                },
                {
                    "data": "room_id",
                    "title": "寝室号",
                    "render": function (data, type, full, meta) {
                        if (data) {
                            return data.name
                        } else {
                            return '-'
                        }
                    }
                },
                {
                    "data": "build_id",
                    "title": "楼宇名称",
                    "render": function (data, type, full, meta) {
                        if (data) {
                            return data.build_name
                        } else {
                            return '-'
                        }
                    }
                },
                {
                    "data": "sex",
                    "title": "性别",
                    "render": function (data, type, full, meta) {
                        if (data == 0) {
                            return '女'
                        } else {
                            return '男'
                        }
                    }
                },
            ],
            /*请求携带参数*/
            "fnServerParams": function (aoData) {
                aoData._rand = Math.random();
                aoData.push(
                    {"name": "sex", "value": sex},
                );
                console.log(aoData)
            },
        });
    }

    function search() {
        table.ajax.reload();
        return false;
    }

    /* 点击查看编辑 */
    $("#tableList").on('click', 'tbody .edit', function () {
        /* 获取当前点击的一行数据 */
        var data = $('#tableList').DataTable().row($(this).parents('tr')).data();
        console.log(data)
        room_name = data.name
        $('#exampleModalLabel').text(room_name)
        $("#exampleModalLabel").attr('room_id', data['id'])
        $("#exampleModalLabel").attr('number', data['number'])
        $("#exampleModalLabel").attr('actual_number', data['actual_number'])
        /* 填充点击寝室的入住学生到模态框中 */
        let tbody = '<thead><tr> <th>序号</th> <th>姓名</th> <th>学号</th> <th>手机号</th> <th>操作</th> </tr></thead>'
        for (let item in data.student_info) {
            let student = data.student_info[item]
            tbody += '<tr><th scope="row">' + String(Number(item) + 1) + '</th>'
            tbody += '<td>' + student.name + '</td>'
            tbody += '<td>' + student.student_number + '</td>'
            tbody += '<td>' + student.phone + '</td>'
            tbody += '<td><a class="move_out">迁出</a></td></tr>'
        }
        $('#student_info').html(tbody)
        // 显示寝室详细信息
        $('#exampleModal').modal('show')
    });

    /* 点击迁入 */
    $('#move_in').on('click', function () {
        const max_number = $('#exampleModalLabel').attr('number')
        const actual_number = $('#exampleModalLabel').attr('actual_number')
        console.log(actual_number, max_number)
        if (actual_number >= max_number) {
            console.log(actual_number, max_number)
            alert('当前寝室已达最大入住人数')
            return
        }
        const room_id = $('#exampleModalLabel').attr('room_id')
        const student_number = $('#student_number').val()
        $.ajax({
            url: '/move-in/',
            data: {
                'room_id': room_id,
                'build_id': build_id,
                'student_number': student_number,
                'sex': sex
            },
            success: function (result) {
                $('#exampleModal').modal('hide')
                alert(result.message)
                table.ajax.reload()
            },
            error: function (err) {
                alert(err)
            }
        })
    })

    /* 点击迁出 */
    $('#student_info').on("click", "tbody .move_out", function () {
        const student = $(this).parent().parent().find("td")
        move_out_student_number = student.eq(1).html()
        move_out_room_id = $("#exampleModalLabel").attr('room_id')
        $('#exampleModal').modal('hide') // 隐藏学生信息框

        // 填充迁出信息，并显示modal框
        let tbody = '<thead><tr><th>姓名</th> <th>学号</th> <th>手机号</th></tr></thead>'
        tbody += '<td>' + student.eq(0).html() + '</td>'
        tbody += '<td>' + student.eq(1).html() + '</td>'
        tbody += '<td>' + student.eq(2).html() + '</td></tr>'
        $('#move_out_room_name').text(room_name)
        $('#move_out_student_info').html(tbody)
        $('#move_out_model').modal('show')
    });

    /* 确定执行迁出功能 */
    $('#move_out_btn').on('click', function () {
        $.ajax({
            url: '/move-out/',
            data: {
                'student_number': move_out_student_number,
                'room_id': move_out_room_id
            },
            success: function (result) {
                $('#exampleModal').modal('hide')
                alert(result.message)
                table.ajax.reload()
            },
            error: function (err) {
                alert(err)
            }
        })
        $('#move_out_model').modal('hide')
    })

    $('#logout').on('click', function () {
        $.ajax({
            url: '/logout/',
            success: function (result) {
                url = result.data.url
                window.location.href = url
            }
        })
    })

    // 点击宿舍管理
    $('#manage').on('click', function () {
        $('.table_body').show()
        $('.student_table_body').hide()
        $('#manage').addClass('active')
        $('#student').removeClass('active')
    })

    // 点击查看学生信息
    $('#student').on('click', function () {
        $('.table_body').hide()
        $('.student_table_body').show()
        $('#manage').removeClass('active')
        $('#student').addClass('active')
    })


</script>
</html>
